﻿using System;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using Falafel.Services;
using Falafel.Services.Web.Services;

namespace Falafel.ViewModel
{
    /// <summary>
    /// Contains all view models used by the view
    /// </summary>
    public class ViewModelManager : ViewModelBase
    {
        #region properties and fields

        public OrderContext Context { get; private set; }

        public DomainDataSource DDS { get; private set; }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (_isBusy != value)
                {
                    _isBusy = value;
                    RaisePropertyChanged("IsBusy");
                }
            }
        }

        private bool _eventsRegistered;

        #endregion

        #region constructors
        public ViewModelManager()
        {
            // setup the Domain Context and the Domain Data Source needed for the View
            Context = new OrderContext();
            DomainDataSource dds = new DomainDataSource
            {
                AutoLoad = false,
                QueryName = "GetOrdersQuery",
                DomainContext = Context
            };
            DDS = dds;
        }
        #endregion

        /// <summary>
        /// Register and view related events on the Domain Data Source
        /// </summary>
        /// <param name="submittedChanges"></param>
        /// <param name="loadedData"></param>
        public void RegisterEvents(EventHandler<SubmittedChangesEventArgs> submittedChanges, EventHandler<LoadedDataEventArgs> loadedData)
        {
            if (_eventsRegistered)
            {
                throw new InvalidOperationException("Cannot register events until the existing events are un-registered");
            }

            DDS.LoadingData += DDS_LoadingData;
            DDS.SubmittingChanges += DDS_SubmittingChanges;
            DDS.LoadedData += DDS_LoadedData;
            DDS.SubmittedChanges += DDS_SubmittedChanges;

            if (submittedChanges != null)
            {
                DDS.SubmittedChanges += submittedChanges;
            }
            if (loadedData != null)
            {
                DDS.LoadedData += loadedData;
            }

            _eventsRegistered = true;
        }

        /// <summary>
        /// Unregister and view related events on the Domain Data Source
        /// </summary>
        /// <param name="submittedChanges"></param>
        /// <param name="loadedData"></param>
        public void UnRegisterEvents(EventHandler<SubmittedChangesEventArgs> submittedChanges, EventHandler<LoadedDataEventArgs> loadedData)
        {
            DDS.LoadingData -= DDS_LoadingData;
            DDS.SubmittingChanges -= DDS_SubmittingChanges;
            DDS.LoadedData -= DDS_LoadedData;
            DDS.SubmittedChanges -= DDS_SubmittedChanges;

            if (submittedChanges != null)
            {
                DDS.SubmittedChanges -= submittedChanges;
            }
            if (loadedData != null)
            {
                DDS.LoadedData -= loadedData;
            }

            _eventsRegistered = false;
        }

        void DDS_SubmittedChanges(object sender, SubmittedChangesEventArgs e)
        {
            IsBusy = false;
        }

        void DDS_LoadedData(object sender, LoadedDataEventArgs e)
        {
            IsBusy = false;
        }

        void DDS_SubmittingChanges(object sender, SubmittingChangesEventArgs e)
        {
            IsBusy = true;
        }

        void DDS_LoadingData(object sender, LoadingDataEventArgs e)
        {
            IsBusy = true;
        }

        public void LoadLookupEntities()
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                return;
            }

            // Load the States into the shared context
            Context.Load(Context.GetStatesQuery(), false);
            Context.Load(Context.GetFalafelUsersQuery(), false);
            Context.Load(Context.GetLoginsQuery(), false);
        }

        public void Load()
        {
            IsBusy = true;
            DDS.Load();
        }

        public virtual void SubmitChanges()
        {
            if (!DDS.IsBusy)
            {
                DDS.SubmitChanges();
            }
        }

        public virtual void RejectChanges()
        {
            if (!DDS.IsBusy)
            {
                DDS.RejectChanges();
            }
        }

        public virtual void Reload()
        {
            if (!DDS.IsBusy)
            {
                DDS.Clear();
                DDS.Load();
            }
        }

        public virtual void SetFilterDescriptor(string filter)
        {
            try
            {
                // if there's no text if the search box remove the filterdescriptor
                if (string.IsNullOrWhiteSpace(filter))
                {
                    DDS.FilterDescriptors.Clear();
                    return;
                }

                FilterDescriptor fd;
                if (DDS.FilterDescriptors.Count == 0)
                {
                    // if there's no filterdescriptor to change, add one
                    fd = new FilterDescriptor("Total", FilterOperator.IsGreaterThan, filter);

                    DDS.FilterDescriptors.Add(fd);
                }
                else
                {
                    // if there's a filterdescriptor, just change the value
                    fd = DDS.FilterDescriptors[0];
                    fd.Value = filter;
                }
            }
            finally
            {
                DDS.Load();
            }
        }

        public void MakeOrderCalifornia(int id, Action<InvokeOperation> changeStatusCompleted)
        {
            Context.MakeOrderCalifornia(id, changeStatusCompleted, null);
        }
    }




























    ///// <summary>
    ///// Contains all view models used by the view
    ///// </summary>
    //public class ViewModelManager
    //{
    //    #region properties

    //    public OrderContext OrderContext { get; set; }

    //    #endregion

    //    #region constructors
    //    public ViewModelManager()
    //    {
    //        OrderContext = new OrderContext();
    //    }
    //    #endregion

    //    public virtual void Submit()
    //    {
    //        if (!OrderContext.IsSubmitting)
    //        {
    //            OrderContext.SubmitChanges(OnSubmitCompleted, null);
    //        }
    //    }

    //    public virtual void Cancel()
    //    {
    //        if (!OrderContext.IsSubmitting)
    //        {
    //            OrderContext.RejectChanges();
    //        }
    //    }

    //    private void OnSubmitCompleted(SubmitOperation submitOperation)
    //    {
    //        if (submitOperation.HasError)
    //        {
    //            MessageBox.Show(string.Format("Submit Failed: {0}", submitOperation.Error.Message));                
    //        }
    //    }


    //    public void LoggedIn()
    //    {
    //        if (!WebContext.Current.User.IsAuthenticated)
    //        {
    //            return;
    //        }

    //        // Load the States into the shared context
    //        OrderContext.Load(OrderContext.GetStatesQuery(), false);
    //        OrderContext.Load(OrderContext.GetFalafelUsersQuery(), false);
    //        OrderContext.Load(OrderContext.GetLoginsQuery(), false);
    //    }

    //}

}
